package com.app.shortvideo.widget

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.annotation.ColorInt
import androidx.core.content.res.ResourcesCompat
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.app.shortvideo.R
import com.blankj.utilcode.util.SizeUtils
import kotlin.math.abs

class MSwipeRefreshLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
    SwipeRefreshLayout(context, attrs) {
    @ColorInt
    private val mColorSchemeResId: Int
    private var lastX = 0f
    private var lastY = 0f

    init {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.MSwipeRefreshLayout)
        mColorSchemeResId = ta.getColor(
            R.styleable.MSwipeRefreshLayout_colorSchemeResId,
            ResourcesCompat.getColor(resources, com.app.library.R.color.color_main, null)
        )
        val topOffset = ta.getDimension(R.styleable.MSwipeRefreshLayout_progressTopOffset, -1f)
        ta.recycle()

        if (topOffset != -1f) {
            setProgressViewOffset(true, 0, topOffset.toInt())
        }
        setColorSchemeColors(
            mColorSchemeResId,
            mColorSchemeResId,
            mColorSchemeResId,
            mColorSchemeResId
        )
    }

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            lastX = ev.x
            lastY = ev.y
        } else if (ev.action == MotionEvent.ACTION_MOVE) {
            val dx = ev.x - lastX
            val dy = ev.y - lastY
            return if (abs(dx) > dy || dy < SizeUtils.dp2px(50f) || abs(dx) > SizeUtils.dp2px(50f)) {
                false
            } else {
                super.onInterceptTouchEvent(ev)
            }
        }
        return super.onInterceptTouchEvent(ev)
    }
}